package com.example.spring_config.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.spring_config.dao.PermissionDao;
import com.example.spring_config.mapper.Permission;
import com.example.spring_config.mapper.RolePermission;
import com.example.spring_config.mapper.UserRole;
import com.example.spring_config.service.PermissionRoleRelationService;
import com.example.spring_config.service.PermissionService;
import com.example.spring_config.service.UserRoleRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionDao, Permission> implements PermissionService {

    @Autowired
    private UserRoleRelationService roleRelationService;
    @Autowired
    private PermissionRoleRelationService permissionRoleRelationService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private PermissionDao permissionDao;

    /**
     * 获取用户的菜单权限
     * @param uid
     * @return
     */
    @Override
    public Set<Permission> getUserPermission(String uid) {
        Set<Permission> permissions = new HashSet<>();
        // 获取用户拥有的角色id
        List<UserRole> u_id = roleRelationService.list(new QueryWrapper<UserRole>().eq("u_id", uid));
        // 获取角色对应的权限id
        for (UserRole rid : u_id) {
            List<RolePermission> r_id = permissionRoleRelationService.list(new QueryWrapper<RolePermission>().eq("r_id", rid.getRId()));
            for (RolePermission pid : r_id) {
                Permission one = permissionService.getOne(new QueryWrapper<Permission>().eq("id", pid.getPId()).eq("type", "菜单"));
                if(one!=null){
                    permissions.add(one);
                    if(!one.getPId().equals("")){
                        // 获取父权限
                        Permission id = permissionService.getOne(new QueryWrapper<Permission>().eq("id", one.getPId()).eq("type", "菜单"));
                        if(id!=null){
                            permissions.add(id);
                        }
                    }
                }

            }
        }
        return permissions;
    }

    /**
     * 根据用户id获取用户权限的url
     * @param uid
     * @return
     */
    @Override
    public Set<String> getUserPermissionUrlByRid(String uid){
        return permissionDao.getPermissionUrlByUid(uid);
    }
}
